package com.ibeeking.found.content.cp.rest.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ibeeking.found.common.entity.KeyValue;
import com.ibeeking.found.common.entity.common.ArticleSettingDTO;
import com.ibeeking.found.common.enums.PublishStatusEnum;
import com.ibeeking.found.common.utils.DataUtils;
import com.ibeeking.found.common.utils.UserUtils;
import com.ibeeking.found.content.api.common.dto.MemberInfoDTO;
import com.ibeeking.found.content.api.feign.ContentMemberBClient;
import com.ibeeking.found.content.cp.rest.service.IArticleCommentService;
import com.ibeeking.found.content.cp.rest.service.IArticleService;
import com.ibeeking.found.content.service.common.dos.ArticleCommentDO;
import com.ibeeking.found.content.service.common.param.ArticleCommentParam;
import com.ibeeking.found.content.service.common.query.ArticleCommentPageQuery;
import com.ibeeking.found.content.service.common.query.ArticleQuery;
import com.ibeeking.found.content.service.common.vo.ArticleCommentVO;
import com.ibeeking.found.content.service.common.vo.ArticleVO;
import com.ibeeking.found.content.service.mapper.ArticleCommentMapper;
import com.ibeeking.found.system.api.feign.SystemCommonFeignCClient;
import com.ibeeking.nematos.utils.bean.BeanUtil;
import com.ibeeking.nematos.utils.data.Collections3;
import com.ibeeking.nematos.utils.json.JsonUtils;
import com.ibeeking.nematos.utils.result.ResponseResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @ClassName ArticleCommentServiceImpl
 * @Description
 * @Author ibeeking
 * @Date 2022-02-21 16:01
 **/
@Service
public class ArticleCommentServiceImpl extends ServiceImpl<ArticleCommentMapper, ArticleCommentDO> implements IArticleCommentService {

    @Resource
    private ArticleCommentMapper articleCommentMapper;
    @Resource
    private IArticleService articleServiceImpl;
    @Resource
    private ContentMemberBClient contentMemberBClient;
    @Resource
    private SystemCommonFeignCClient systemCommonFeignCClient;

    @Override
    public Page<ArticleCommentVO> pageList(ArticleCommentPageQuery articleCommentPageQuery) {
        LambdaQueryWrapper<ArticleCommentDO> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(articleCommentPageQuery.getArticleId() != null, ArticleCommentDO::getArticleId, articleCommentPageQuery.getArticleId());
        wrapper.ge(StringUtils.isNotBlank(articleCommentPageQuery.getCreateTimeStart()), ArticleCommentDO::getCreateTime, articleCommentPageQuery.getCreateTimeStart());
        wrapper.le(StringUtils.isNotBlank(articleCommentPageQuery.getCreateTimeEnd()), ArticleCommentDO::getCreateTime, articleCommentPageQuery.getCreateTimeEnd());
        wrapper.orderByDesc(ArticleCommentDO::getCreateTime);
        Page<ArticleCommentDO> pages = articleCommentMapper.selectPage(new Page<ArticleCommentDO>(articleCommentPageQuery.getPageNum(), articleCommentPageQuery.getPageSize()), wrapper);
        Page<ArticleCommentVO> articleCommentVOPage = BeanUtil.convertPage(pages, ArticleCommentVO.class);
        List<ArticleCommentVO> records = articleCommentVOPage.getRecords();
        wrapperVO(records);
        return articleCommentVOPage;
    }

    @Override
    public ArticleCommentVO view(Long id) {
        ArticleCommentDO articleCommentDO = articleCommentMapper.selectById(id);
        ArticleCommentVO articleCommentVO = JsonUtils.fromJson(articleCommentDO, ArticleCommentVO.class);
        wrapperVO(Collections3.newArrayList(articleCommentVO));
        return articleCommentVO;
    }

    @Override
    public Boolean save(ArticleCommentParam articleCommentParam) {
        Long userId = UserUtils.getUserId();
        if (articleCommentParam.getMemberId() == null) {
            articleCommentParam.setMemberId(userId);
        }
        DataUtils.falseThrowException(userId.equals(articleCommentParam.getMemberId()), "您只能修改您自己发表的评论!");
        ResponseResult<ArticleSettingDTO> articleSettingDTOResult = systemCommonFeignCClient.articleSettingView();
        ArticleSettingDTO articleSettingVO = articleSettingDTOResult.getData();
        List<KeyValue> sensitiveWords = Optional.ofNullable(articleSettingVO).map(ArticleSettingDTO::getSensitiveWords).orElse(Collections3.emptyList());
        if (Collections3.isNotEmpty(sensitiveWords)) {
            List<String> sensitiveWordStrs = sensitiveWords.stream().map(x -> x.getValue().toString()).collect(Collectors.toList());
            for (String sensitiveWordStr : sensitiveWordStrs) {
                DataUtils.trueThrowException(articleCommentParam.getContent().contains(sensitiveWordStr), "您的评论内容包含敏感词: " + sensitiveWordStr);
            }
        }
        ArticleCommentDO articleCommentDO = JsonUtils.fromJson(articleCommentParam, ArticleCommentDO.class);
        if (articleCommentDO.getId() == null) {
            articleCommentDO.setPublishStatus(PublishStatusEnum.ENABLE.getValue());
            articleCommentMapper.insert(articleCommentDO);
        } else {
            articleCommentMapper.updateById(articleCommentDO);
        }
        return true;
    }


    public void wrapperVO(List<ArticleCommentVO> vos) {
        if (Collections3.isEmpty(vos)) {
            return;
        }
        Set<Long> articleIds = vos.stream().map(ArticleCommentVO::getArticleId).collect(Collectors.toSet());
        Set<Long> memberIds = vos.stream().map(ArticleCommentVO::getMemberId).collect(Collectors.toSet());
        List<ArticleVO> articleVOList = articleServiceImpl.list(new ArticleQuery().setIds(Collections3.newArrayList(articleIds)));
        Map<Long, String> articleMap = articleVOList.stream().collect(Collectors.toMap(ArticleVO::getId, ArticleVO::getTitle));
        ResponseResult<List<MemberInfoDTO>> responseResult = contentMemberBClient.infoList(memberIds);
        List<MemberInfoDTO> memberInfoDTOList = Optional.ofNullable(responseResult.getData()).orElse(Collections3.emptyList());
        Map<Long, MemberInfoDTO> memberMap = memberInfoDTOList.stream().collect(Collectors.toMap(MemberInfoDTO::getId, x -> x));
        for (ArticleCommentVO vo : vos) {
            vo.setArticleTitle(articleMap.get(vo.getArticleId()));
            MemberInfoDTO memberInfoDTO = memberMap.get(vo.getMemberId());
            if (memberInfoDTO != null) {
                vo.setMemberName(memberInfoDTO.getName());
                vo.setMemberName(memberInfoDTO.getNickname());
            }
        }
    }
}
